// 专注记录管理
import { ref } from "vue";
import { dateformat } from "@/utils/date";
import { DB_KEY_FOCUS_RECORDS } from "./constant.js";

/**
 * 专注记录列表
 */
export const focusRecords = ref([]);

/**
 * 保存专注记录到本地存储
 */
export const saveFocusRecord = () => {
  utools.dbStorage.setItem(DB_KEY_FOCUS_RECORDS, JSON.stringify(focusRecords.value));
};

/**
 * 从本地存储加载专注记录
 */
export const loadFocusRecord = () => {
  let data = utools.dbStorage.getItem(DB_KEY_FOCUS_RECORDS);
  if (data) {
    // 过滤出今天及今天之后的数据
    const records = JSON.parse(data);
    const today = dateformat(new Date(), "YYYY-MM-DD");
    const filteredRecords = records.filter((record) => {
      // 提取记录中的日期部分（前10个字符为 YYYY-MM-DD）
      const recordDate = record.substring(0, 10);
      // 比较日期，保留今天及之后的记录
      return recordDate >= today;
    });

    focusRecords.value = filteredRecords;

    //过滤后的数据再次保持
    saveFocusRecord();
  } else {
    focusRecords.value = [];
    saveFocusRecord();
  }
};

/**
 * 添加新的专注记录
 */
export const addFocusRecord = () => {
  // 添加当前时间作为记录
  const now = dateformat(new Date(), "YYYY-MM-DD-HH-mm-ss");
  focusRecords.value.push(now);
  // 保存
  saveFocusRecord();
};
